package com.pethub.dao.daoimpl;

import com.pethub.dao.UserDao;
import com.pethub.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 2017-12-3
 * @Version 1.0
 * @Author harden
 */
@Repository("userDao")
public class UserDaoImpl  implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;
    private Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }

    public User load(String id) throws Exception {
        return (User) this.getCurrentSession().load(User.class, Integer.parseInt(id));
    }

    public User get(String id) throws Exception {
        return (User) this.getCurrentSession().get(User.class, Integer.parseInt(id));
    }

    public List<User> findAll(String hql) throws Exception {
        List<User> acctUsers = this.getCurrentSession().createQuery(hql).setCacheable(true).list();
        return acctUsers;
    }

    public User save(User entity) throws Exception {
        Integer id= (Integer) getCurrentSession().save(entity);
        this.flush();
        return this.get(id.toString());
    }

    public void saveOrUpdate(User entity) throws Exception {
         getCurrentSession().saveOrUpdate(entity);
    }

    public void delete(String id) throws Exception {
       this. getCurrentSession().delete(this.load(id));
    }

    public void flush() throws Exception {
        this.getCurrentSession().flush();;
    }
    @SuppressWarnings("warning")
    public User getByEmail(String email) throws  Exception{
        List<User> users= (List<User>) this.getCurrentSession().createQuery("from com.pethub.entity.User u where u.email= '"+email+"'").list();
       if(users.size()>0)
       {
           return users.get(0);
       }else {
           return null;
       }
    }
}
